//
//  ANUserLogonViewController.m
//  Ants
//
//  Created by ZHM on 16/8/6.
//  Copyright © 2016年 ZHM. All rights reserved.
//

#import "ANUserLogonViewController.h"
#import "ANUserPasswordViewController.h"

#define ANLoginOKNote @"loginOKNote"

@interface ANUserLogonViewController ()
{
    UIView *bgView;
//    UITextField *phone;
//    UITextField *code;
    UINavigationBar *customNavigationBar;
    UIButton *yzButton;
}
@property(nonatomic, copy) NSString *userPhoneNum;
@property(assign, nonatomic) NSInteger timeCount;
@property(strong, nonatomic) NSTimer *timer;
//验证码
@property(copy, nonatomic) NSString *smsId;
@end

@implementation ANUserLogonViewController

- (instancetype)init {
    if (self = [super init]){
        self.hidesBottomBarWhenPushed = YES;
    }
    return self;
}
- (void)viewDidLoad
{
    [super viewDidLoad];

    self.title=@"注册1/3";
    self.navigationController.navigationBarHidden = NO;
    [[UINavigationBar appearance] setBarTintColor:[UIColor whiteColor]];
    self.view.backgroundColor=[UIColor colorWithRed:240/255.0f green:240/255.0f blue:240/255.0f alpha:1];
    
     [self createTextFields];
}


-(void)createTextFields
{
    UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(30, 75, self.view.frame.size.width-90, 30)];
    label.text=@"请输入您的手机号码";
    label.textColor=[UIColor grayColor];
    label.textAlignment = NSTextAlignmentLeft;
    label.font=[UIFont systemFontOfSize:13];
    [self.view addSubview:label];
    
    
    CGRect frame = [UIScreen mainScreen].bounds;
    bgView = [[UIView alloc]initWithFrame:CGRectMake(10, 110, frame.size.width-20, 100)];
    bgView.layer.cornerRadius=3.0;
    bgView.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:bgView];
    
    phone = [self createTextFielfFrame:CGRectMake(80, 10, 200, 30) font:[UIFont systemFontOfSize:14] placeholder:@"11位手机号"];
    phone.clearButtonMode = UITextFieldViewModeWhileEditing;
    phone.keyboardType=UIKeyboardTypeNumberPad;
    phone.tag = 100;
    [phone addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    code=[self createTextFielfFrame:CGRectMake(80, 60, 100, 30) font:[UIFont systemFontOfSize:14]  placeholder:@"7位数字" ];
    code.clearButtonMode = UITextFieldViewModeWhileEditing;
    code.tag = 101;
    [code addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    //密文样式
    code.secureTextEntry=YES;
    code.keyboardType=UIKeyboardTypeNumberPad;
    
    
    UILabel *phonelabel=[[UILabel alloc]initWithFrame:CGRectMake(20, 12, 50, 25)];
    phonelabel.text=@"手机号";
    phonelabel.textColor=[UIColor blackColor];
    phonelabel.textAlignment = NSTextAlignmentLeft;
    phonelabel.font=[UIFont systemFontOfSize:14];
    
    UILabel *codelabel=[[UILabel alloc]initWithFrame:CGRectMake(20, 62, 50, 25)];
    codelabel.text=@"验证码";
    codelabel.textColor=[UIColor blackColor];
    codelabel.textAlignment = NSTextAlignmentLeft;
    codelabel.font=[UIFont systemFontOfSize:14];
    
    
    yzButton=[[UIButton alloc]initWithFrame:CGRectMake(bgView.frame.size.width-100-20, 62, 100, 30)];
    [yzButton setTitle:@"获取验证码" forState:UIControlStateNormal];
    [yzButton setTitleColor:[UIColor colorWithRed:180/255.0f green:180/255.0f blue:180/255.0f alpha:.3] forState:UIControlStateNormal];
    yzButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [yzButton addTarget:self action:@selector(getValidCode:) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:yzButton];
    
    UIImageView *line1=[self createImageViewFrame:CGRectMake(20, 50, bgView.frame.size.width-40, 1) imageName:nil color:[UIColor colorWithRed:180/255.0f green:180/255.0f blue:180/255.0f alpha:.3]];
    
    UIButton *landBtn=[self createButtonFrame:CGRectMake(10, bgView.frame.size.height+bgView.frame.origin.y+30,self.view.frame.size.width-20, 37) backImageName:nil title:@"下一步" titleColor:[UIColor whiteColor]  font:[UIFont systemFontOfSize:17] target:self action:@selector(next)];
    landBtn.backgroundColor=[UIColor colorWithRed:248/255.0f green:144/255.0f blue:34/255.0f alpha:1];
    landBtn.layer.cornerRadius=5.0f;
    _landBtn = landBtn;
    
    [bgView addSubview:phone];
    [bgView addSubview:code];
    
    [bgView addSubview:phonelabel];
    [bgView addSubview:codelabel];
    [bgView addSubview:line1];
    [self.view addSubview:landBtn];
    
}

- (void)textFieldDidChange:(UITextField *)textField {
    if (textField.tag == 100) {
        if (textField.text.length > 11) {
            textField.text = [textField.text substringToIndex:11];
        }
        if (textField.text.length == 11) {
            [yzButton setTitleColor:[UIColor colorWithRed:248/255.0f green:144/255.0f blue:34/255.0f alpha:1] forState:UIControlStateNormal];
        }else {
            [yzButton setTitleColor:[UIColor colorWithRed:180/255.0f green:180/255.0f blue:180/255.0f alpha:.3] forState:UIControlStateNormal];
        }
    } else if (textField.tag == 101) {
        if (textField.text.length > 7) {
            textField.text = [textField.text substringToIndex:7];
        }
    }
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [phone resignFirstResponder];
    [code resignFirstResponder];
}

- (void)getValidCode:(UIButton *)sender
{
    if ([phone.text isEqualToString:@""])
    {
        return;
    }
    else if (phone.text.length <11)
    {
        return;
    }
    _userPhoneNum = phone.text;
    
    
    
    //[self setRequestSmsCodeBtnCountDown];//////////////
    
    
    /**
     *  请求短信信息
     *
     *  @param number   电话号码
     *  @param content  短信内容
     *  @param sendTime 发送时间（可为空）
     *  @param block    返回结果，含smsId,可用于查询短信发送状态
     */
//    + (void)requestSMSInbackgroundWithPhoneNumber:(NSString*)number
//Content:(NSString*)content
//andSendTime:(NSString*)sendTime
//resultBlock:(BmobIntegerResultBlock)block;
    
    
    //字符串转NSDate
//    NSDateFormatter *format = [[NSDateFormatter alloc] init];
//    format.dateFormat = @"yyyy-MM-dd HH:mm";
//    NSString *dateStr = [format stringFromDate:[NSDate date]];
//    [BmobSMS requestSMSInbackgroundWithPhoneNumber:_userPhoneNum Content:@"zhm登录验证码:" andSendTime:dateStr resultBlock:^(int number, NSError *error) {
//        if (error) {
//            NSLog(@"%@",error);
//            UIAlertView *tip = [[UIAlertView alloc] initWithTitle:nil message:@"请输入正确的手机号码" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//            [tip show];
//        } else {
//            //获得smsID
//            self.smsId = [NSString stringWithFormat:@"%d",number];
//            NSLog(@"sms ID：%d",number);
//            //设置不可点击
//            [self setRequestSmsCodeBtnCountDown];
//        }
//    }];
    
    //请求验证码
    [BmobSMS requestSMSCodeInBackgroundWithPhoneNumber:_userPhoneNum andTemplate:@"AntsTemp" resultBlock:^(int number, NSError *error) {
        if (error) {
            NSLog(@"%@",error);
            UIAlertView *tip = [[UIAlertView alloc] initWithTitle:nil message:@"请输入正确的手机号码" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [tip show];
        } else {
            //获得smsID
            self.smsId = [NSString stringWithFormat:@"%d",number];
            NSLog(@"sms ID：%d",number);
            //设置不可点击
            [self setRequestSmsCodeBtnCountDown];
        }
    }];
}


-(void)setRequestSmsCodeBtnCountDown{
    yzButton.userInteractionEnabled = NO;
    self.timeCount = 60;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(reduceTime:) userInfo:yzButton repeats:YES];
}

- (void)reduceTime:(NSTimer *)codeTimer {
    self.timeCount--;
    if (self.timeCount == 0) {
        [yzButton setTitle:@"重新获取验证码" forState:UIControlStateNormal];
        [yzButton setTitleColor:[UIColor colorWithRed:248/255.0f green:144/255.0f blue:34/255.0f alpha:1] forState:UIControlStateNormal];
        UIButton *info = codeTimer.userInfo;
        info.enabled = YES;
        yzButton.userInteractionEnabled = YES;
        [self.timer invalidate];
    } else {
        NSString *str = [NSString stringWithFormat:@"%lu秒后重获取", (long)self.timeCount];
        [yzButton setTitle:str forState:UIControlStateNormal];
        yzButton.userInteractionEnabled = NO;
    }
}


-(UITextField *)createTextFielfFrame:(CGRect)frame font:(UIFont *)font placeholder:(NSString *)placeholder
{
    UITextField *textField=[[UITextField alloc]initWithFrame:frame];
    
    textField.font=font;
    
    textField.textColor=[UIColor grayColor];
    
    textField.borderStyle=UITextBorderStyleNone;
    
    textField.placeholder=placeholder;
    
    return textField;
}

-(UIImageView *)createImageViewFrame:(CGRect)frame imageName:(NSString *)imageName color:(UIColor *)color
{
    UIImageView *imageView=[[UIImageView alloc]initWithFrame:frame];
    
    if (imageName)
    {
        imageView.image=[UIImage imageNamed:imageName];
    }
    if (color)
    {
        imageView.backgroundColor=color;
    }
    
    return imageView;
}

-(UIButton *)createButtonFrame:(CGRect)frame backImageName:(NSString *)imageName title:(NSString *)title titleColor:(UIColor *)color font:(UIFont *)font target:(id)target action:(SEL)action
{
    UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame=frame;
    if (imageName)
    {
        [btn setBackgroundImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    }
    
    if (font)
    {
        btn.titleLabel.font=font;
    }
    
    if (title)
    {
        [btn setTitle:title forState:UIControlStateNormal];
    }
    if (color)
    {
        [btn setTitleColor:color forState:UIControlStateNormal];
    }
    if (target&&action)
    {
        [btn addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    }
    return btn;
}

//下一步
-(void)next
{
    
//    if ([phone.text isEqualToString:@""])
//    {
//        [SVProgressHUD showInfoWithStatus:@"亲,请输入注册手机号码"];
//        return;
//    }
//    else if (phone.text.length <11)
//    {
//        [SVProgressHUD showInfoWithStatus:@"您输入的手机号码格式不正确"];
//        return;
//    }
//    else if ([code.text isEqualToString:@""])
//    {
//        [SVProgressHUD showInfoWithStatus:@"亲,请输入验证码"];
//        return;
//    }
//    else if (self.smsId.length == 0)
//    {
//        [SVProgressHUD showInfoWithStatus:@"验证码错误"];
//        return;
//   }
//    [BmobSMS verifySMSCodeInBackgroundWithPhoneNumber:_userPhoneNum  andSMSCode:code.text resultBlock:^(BOOL isSuccessful, NSError *error) {
//        if (isSuccessful) {
//            ANUserPasswordViewController *vc = [[ANUserPasswordViewController alloc]init];
//            vc.userPhoneNum = _userPhoneNum;
//            vc.code = code.text;
//            [self.navigationController pushViewController:vc animated:YES];
//        }else {
//            ANLog(@"错误:------%@",error);
//            [SVProgressHUD showInfoWithStatus:@"验证错误"];
//        }
//    }];
    
    //测试直接跳过
    ANUserPasswordViewController *vc = [[ANUserPasswordViewController alloc]init];
    vc.userPhoneNum = _userPhoneNum;
    vc.code = code.text;
    [self.navigationController pushViewController:vc animated:YES];
}


@end
